/**
 * 商家端 API 服务管理
 * 统一管理所有后端接口调用
 */

import { getApiConfig } from './config';

// API 基础配置
const envConfig = getApiConfig();
const API_CONFIG = {
  baseURL: envConfig.baseURL,
  timeout: envConfig.timeout,
  header: {
    'content-type': 'application/json'
  }
}

/**
 * 通用请求方法
 */
const request = (options: {
  url: string,
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE',
  data?: any,
  header?: any
}): Promise<any> => {
  return new Promise((resolve, reject) => {
    // 获取商家端token
    const token = wx.getStorageSync('merchantToken')
    
    // 添加调试日志：检查token
    console.log('=== 发起API请求 ===')
    console.log('请求URL:', options.url)
    console.log('Token存在:', !!token)
    console.log('Token值:', token ? token.substring(0, 20) + '...' : '无')
    
    // 对于 GET 请求，过滤掉 undefined、null 和空字符串的参数，避免转换为字符串 "undefined"
    let requestData = options.data;
    const method = options.method || 'GET';
    if (method === 'GET' && requestData) {
      // 确保 requestData 是对象类型
      if (typeof requestData === 'object' && !Array.isArray(requestData)) {
        const filteredData: any = {};
        Object.keys(requestData).forEach(key => {
          const value = requestData[key];
          // 只保留有意义的参数值（排除 undefined、null 和空字符串）
          if (value !== undefined && value !== null && value !== '') {
            filteredData[key] = value;
          }
        });
        // 如果过滤后有参数，使用过滤后的数据，否则使用 undefined
        requestData = Object.keys(filteredData).length > 0 ? filteredData : undefined;
      }
      // 如果不是对象类型（如字符串、数字等），直接使用原值
    }
    
    wx.request({
      url: API_CONFIG.baseURL + options.url,
      method: method,
      data: requestData,
      header: {
        ...API_CONFIG.header,
        ...options.header,
        'Authorization': token ? `Bearer ${token}` : ''
      },
      timeout: API_CONFIG.timeout,
      success: (res) => {
        // 调试日志：打印请求和响应
        console.log('=== API请求成功 ===')
        console.log('请求URL:', API_CONFIG.baseURL + options.url)
        console.log('请求方法:', options.method || 'GET')
        console.log('请求参数:', requestData)
        console.log('请求头Authorization:', token ? 'Bearer ' + token.substring(0, 20) + '...' : '无')
        console.log('响应状态:', res.statusCode)
        console.log('响应数据:', res.data)
        console.log('==================')
        
        // 统一处理响应
        if (res.statusCode === 200) {
          let responseData: any = res.data
          if (typeof res.data === 'string') {
            try {
              responseData = JSON.parse(res.data)
            } catch (parseError) {
              console.warn('响应JSON解析失败，使用原始数据', parseError)
            }
          }

          if (responseData && responseData.code === 200) {
            resolve(responseData)
          } else {
            // 业务错误处理
            wx.showToast({
              title: (responseData && responseData.msg) || '请求失败',
              icon: 'none'
            })
            reject(responseData)
          }
        } else if (res.statusCode === 401) {
          // token过期，跳转到登录页
          wx.showToast({
            title: '登录已过期',
            icon: 'none'
          })
          wx.redirectTo({
            url: '/pages/auth/auth'
          })
          reject(res)
        } else {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          })
          reject(res)
        }
      },
      fail: (error) => {
        // 调试日志：打印错误信息
        console.error('=== API请求失败 ===')
        console.error('请求URL:', API_CONFIG.baseURL + options.url)
        console.error('错误信息:', error)
        console.error('==================')
        
        wx.showToast({
          title: '网络连接失败',
          icon: 'none'
        })
        reject(error)
      }
    })
  })
}

/**
 * 商家认证相关接口
 */
export const AuthAPI = {
  // 发送短信验证码
  sendSmsCode: (params: { phone: string; type: 'login' | 'register' }) => {
    return request({
      url: `/merchant/auth/sms/send/${params.phone}`,
      method: 'POST'
    })
  },

  // 商家注册
  merchantRegister: (params: {
    phone: string;
    smsCode: string;
    password: string;
    confirmPassword: string;
    agreeProtocol: boolean;
  }) => {
    return request({
      url: '/merchant/auth/register',
      method: 'POST',
      data: params
    })
  },

  // 手机号密码登录
  merchantLogin: (params: { phone: string; password: string; loginType: 'password' }) => {
    return request({
      url: '/merchant/auth/login',
      method: 'POST',
      data: params
    })
  },

  // 手机号验证码登录
  merchantSmsLogin: (params: { phone: string; smsCode: string; loginType: 'sms' }) => {
    return request({
      url: '/merchant/auth/login',
      method: 'POST',
      data: params
    })
  },

  // 微信授权登录
  wechatLogin: (params: { code: string }) => {
    return request({
      url: '/merchant/login/wechat',
      method: 'POST',
      data: params
    })
  },

  // 忘记密码（通过手机验证码重置密码）
  forgotPassword: (params: {
    phone: string;
    smsCode: string;
    newPassword: string;
    confirmPassword: string;
  }) => {
    return request({
      url: '/merchant/info/account/forgot-password',
      method: 'POST',
      data: params
    })
  },

  // 提交商家入驻申请
  submitApplication: (params: {
    merchantName: string;
    merchantType: number;
    contactName: string;
    contactPhone: string;
    contactEmail: string;
    address: string;
    description?: string;
    businessLicense: string;
    idCardFront: string;
    idCardBack: string;
    otherCredentials?: string[];
    agreeAgreement: boolean;
    remark?: string;
  }) => {
    return request({
      url: '/merchant/application/submit',
      method: 'POST',
      data: params
    })
  },

  // 查询入驻申请历史记录
  getApplicationHistory: () => {
    return request({
      url: '/merchant/application/history',
      method: 'GET'
    })
  },

  // 获取最新的入驻申请记录
  getLatestApplication: () => {
    return request({
      url: '/merchant/application/latest',
      method: 'GET'
    })
  },

  // 退出登录
  logout: () => {
    return request({
      url: '/merchant/auth/logout',
      method: 'POST'
    })
  }
}

/**
 * 商家端订单管理接口
 */
export const MerchantAPI = {
  // 获取订单列表
  getOrderList: (params: any) => {
    return request({
      url: '/merchant/orders/list',
      method: 'GET',
      data: params
    })
  },

  // 确认订单
  acceptOrder: (params: { orderId: number }) => {
    return request({
      url: '/merchant/orders/accept',
      method: 'POST',
      data: params
    })
  },

  // 开始制作
  startCooking: (params: { orderId: number }) => {
    return request({
      url: '/merchant/orders/start-cooking',
      method: 'POST',
      data: params
    })
  },

  // 制作完成
  readyForPickup: (params: { orderId: number }) => {
    return request({
      url: '/merchant/orders/ready-for-pickup',
      method: 'POST',
      data: params
    })
  },

  // 取消订单
  cancelOrder: (params: { orderId: number; reason?: string }) => {
    return request({
      url: '/merchant/orders/cancel',
      method: 'POST',
      data: params
    })
  },

  // 获取订单详情
  getOrderDetail: (orderId: number) => {
    return request({
      url: `/merchant/orders/detail/${orderId}`,
      method: 'GET'
    })
  },

  // 获取订单联系信息
  getOrderContactInfo: (orderId: number) => {
    return request({
      url: `/merchant/orders/${orderId}/contact-info`,
      method: 'GET'
    })
  },

  // 记录联系操作
  recordContactAction: (orderId: number, params: any) => {
    return request({
      url: `/merchant/orders/${orderId}/contact-record`,
      method: 'POST',
      data: params
    })
  },

  // 获取工作台数据
  getWorkbenchData: () => {
    return request({
      url: '/merchant/workbench/dashboard',
      method: 'GET'
    })
  },

  // 获取销售趋势
  getSalesTrend: (params: any) => {
    return request({
      url: '/merchant/workbench/sales-trend',
      method: 'GET',
      data: params
    })
  },

  // 获取门店信息
  getStoreInfo: () => {
    return request({
      url: '/merchant/info',
      method: 'GET'
    })
  },

  // 更新门店信息
  updateStoreInfo: (params: any) => {
    return request({
      url: '/merchant/shop/update-info',
      method: 'PUT',
      data: params
    })
  },

  // 更新营业状态
  updateBusinessStatus: (params: any) => {
    return request({
      url: '/merchant/store/business-status',
      method: 'PUT',
      data: params
    })
  },

  // 更新接单方式
  updateOrderMode: (params: any) => {
    return request({
      url: '/merchant/store/order-mode',
      method: 'PUT',
      data: params
    })
  },

  // 上传背景图
  uploadBackground: (filePath: string) => {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('merchantToken')
      
      wx.uploadFile({
        url: API_CONFIG.baseURL + '/merchant/store/upload-background',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          try {
            let responseData: any = res.data
            if (typeof res.data === 'string') {
              responseData = JSON.parse(res.data)
            }

            if (responseData && responseData.code === 200) {
              resolve(responseData)
            } else {
              reject(responseData)
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  },

  // 上传门店头像
  uploadShopAvatar: (filePath: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('merchantToken')

      wx.uploadFile({
        url: API_CONFIG.baseURL + '/merchant/info/upload-shopAvatar',
        filePath,
        name: 'file',
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          try {
            let responseData: any = res.data
            if (typeof res.data === 'string') {
              responseData = JSON.parse(res.data)
            }

            if (responseData && responseData.code === 200) {
              resolve(responseData)
            } else {
              wx.showToast({
                title: (responseData && responseData.msg) || '上传失败',
                icon: 'none'
              })
              reject(responseData)
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(error)
        }
      })
    })
  },

  // ==================== 分类管理相关 ====================
  getCategoryTree: (params?: { status?: number }) => {
    return request({
      url: '/merchant/category/list',
      method: 'GET',
      data: params
    })
  },

  getCategoryOptions: () => {
    return request({
      url: '/merchant/category/tree',
      method: 'GET'
    })
  },

  getCategoryDetail: (categoryId: number) => {
    return request({
      url: `/merchant/category/${categoryId}`,
      method: 'GET'
    })
  },

  createCategory: (params: {
    name: string;
    parentId?: number | null;
    sortOrder?: number;
    status?: number;
  }) => {
    return request({
      url: '/merchant/category',
      method: 'POST',
      data: params
    })
  },

  updateCategory: (params: {
    categoryId: number;
    name?: string;
    parentId?: number | null;
    sortOrder?: number;
    status?: number;
  }) => {
    return request({
      url: '/merchant/category',
      method: 'PUT',
      data: params
    })
  },

  deleteCategory: (categoryIds: Array<number | string>) => {
    const ids = Array.isArray(categoryIds) ? categoryIds.join(',') : categoryIds;
    return request({
      url: `/merchant/category/${ids}`,
      method: 'DELETE'
    })
  },

  // ==================== 商品管理相关 ====================
  // 获取商品列表
  getProducts: (params?: {
    pageNum?: number;
    pageSize?: number;
    status?: number | string;
    auditStatus?: number | string;
    name?: string;
    categoryId?: number | string;
  }) => {
    return request({
      url: '/merchant/product/list',
      method: 'GET',
      data: params
    })
  },

  // 获取商品详情
  getProductDetail: (productId: number | string) => {
    return request({
      url: `/merchant/product/${productId}`,
      method: 'GET'
    })
  },

  // 获取商品统计
  getProductStatistics: () => {
    return request({
      url: '/merchant/product/statistics',
      method: 'GET'
    })
  },

  // 创建商品并提交审核
  createProduct: (params: any) => {
    return request({
      url: '/merchant/product/submit',
      method: 'POST',
      data: params
    })
  },

  // 修改商品详情并重新提交审核
  updateProduct: (params: any) => {
    return request({
      url: '/merchant/product/submit/update',
      method: 'PUT',
      data: params
    })
  },

  // 更新商品状态（支持批量）
  updateProductStatus: (params: { productIds: Array<number | string>; status: number }) => {
    return request({
      url: '/merchant/product/status',
      method: 'PUT',
      data: params
    })
  },

  // 更新 SKU 价格/库存
  updateProductPriceStock: (params: {
    skuId: number | string;
    price: number;
    stock: number;
    marketPrice?: number;
  }) => {
    return request({
      url: '/merchant/product/sku/price-stock',
      method: 'PUT',
      data: params
    })
  },

  // ==================== 套餐管理相关 ====================
  // 获取套餐列表
  getCombos: (params?: {
    pageNum?: number;
    pageSize?: number;
    name?: string;
    status?: number | string;
  }) => {
    return request({
      url: '/merchant/combo/list',
      method: 'GET',
      data: params
    })
  },

  // 获取套餐详情
  getComboDetail: (comboId: number | string) => {
    return request({
      url: `/merchant/combo/${comboId}`,
      method: 'GET'
    })
  },

  // 创建套餐
  createCombo: (params: {
    name: string;
    description?: string;
    imageUrl?: string;
    marketPrice: number;
    regionPrice: number;
    sortOrder?: number;
    products: Array<{
      productId: number;
      quantity: number;
      sortOrder?: number;
    }>;
  }) => {
    return request({
      url: '/merchant/combo',
      method: 'POST',
      data: params
    })
  },

  // 更新套餐
  updateCombo: (params: {
    comboId: number;
    name: string;
    description?: string;
    imageUrl?: string;
    marketPrice: number;
    regionPrice: number;
    sortOrder?: number;
    products: Array<{
      productId: number;
      quantity: number;
      sortOrder?: number;
    }>;
  }) => {
    return request({
      url: '/merchant/combo',
      method: 'PUT',
      data: params
    })
  },

  // 删除套餐（支持批量）
  deleteCombo: (comboIds: Array<number | string>) => {
    const ids = Array.isArray(comboIds) ? comboIds : [comboIds];
    // 转换为数字数组
    const numIds = ids.map(id => Number(id));
    return request({
      url: `/merchant/combo/${numIds.join(',')}`,
      method: 'DELETE'
    })
  },

  // 批量修改套餐状态
  updateComboStatus: (params: {
    comboIds: Array<number | string>;
    status: number;
  }) => {
    const numIds = params.comboIds.map(id => Number(id));
    return request({
      url: '/merchant/combo/status',
      method: 'PUT',
      data: {
        comboIds: numIds,
        status: params.status
      }
    })
  },

  // 批量操作商品（兼容旧代码）
  batchUpdateProducts: (params: any) => {
    return request({
      url: '/merchant/product/status',
      method: 'PUT',
      data: params
    })
  },

  // 获取评价统计
  getReviewStatistics: () => {
    return request({
      url: '/merchant/review/statistics',
      method: 'GET'
    })
  },

  // 获取评价列表
  getReviews: (params?: {
    pageNum?: number;
    pageSize?: number;
    score?: number;           // 评分筛选：1-5
    repliedFilter?: boolean;   // 回复状态筛选：true-已回复，false-未回复
    content?: string;          // 关键词搜索
  }) => {
    return request({
      url: '/merchant/review/list',
      method: 'GET',
      data: params
    })
  },

  // 获取评价详情
  getReviewDetail: (reviewId: number) => {
    return request({
      url: `/merchant/review/detail/${reviewId}`,
      method: 'GET'
    })
  },

  // 回复评价
  replyToReview: (params: {
    reviewId: number;
    replyContent: string;
  }) => {
    return request({
      url: '/merchant/review/reply',
      method: 'PUT',
      data: params
    })
  },

  // 预览计算评分（不更新数据库）
  previewRating: () => {
    return request({
      url: '/merchant/review/previewRating',
      method: 'GET'
    })
  },

  // 获取退款申请列表
  getRefundApplications: (params: any) => {
    return request({
      url: '/merchant/refund/applications',
      method: 'GET',
      data: params
    })
  },

  // 获取退款申请详情
  getRefundDetail: (refundId: string) => {
    return request({
      url: `/merchant/refund/applications/${refundId}`,
      method: 'GET'
    })
  },

  // 处理退款申请
  handleRefundApplication: (refundId: string, params: any) => {
    return request({
      url: `/merchant/refund/applications/${refundId}/handle`,
      method: 'POST',
      data: params
    })
  },

  // ==================== 消息中心相关 ====================
  
  // 获取消息统计数据
  getMessageStatistics: () => {
    return request({
      url: '/merchant/messages/statistics',
      method: 'GET'
    })
  },

  // 获取消息会话列表
  getMessageSessions: (params?: {
    pageNum?: number;
    pageSize?: number;
    msgType?: 'customer' | 'platform' | 'group';
  }) => {
    return request({
      url: '/merchant/messages/sessions',
      method: 'GET',
      data: params
    })
  },

  // 获取会话聊天记录
  getSessionHistory: (sessionId: number | string, params?: {
    pageNum?: number;
    pageSize?: number;
  }) => {
    return request({
      url: `/merchant/messages/sessions/${String(sessionId)}/history`,
      method: 'GET',
      data: params
    })
  },

  // 发送消息
  sendMessage: (sessionId: number | string, params: {
    content: string;
    messageType?: 'text' | 'image';
  }) => {
    return request({
      url: `/merchant/messages/sessions/${String(sessionId)}/send`,
      method: 'POST',
      data: params
    })
  },

  // 发送优惠券
  sendCoupon: (sessionId: number | string, params: {
    couponTemplateId: string | number;
    customMessage?: string;
  }) => {
    // 根据文档，couponTemplateId应该是Long类型，但前端可能传字符串
    // 确保转换为数字，如果无法转换则保持原值
    const couponTemplateId = typeof params.couponTemplateId === 'string' 
      ? (Number(params.couponTemplateId) || params.couponTemplateId)
      : params.couponTemplateId;
    
    const payload = {
      couponTemplateId: couponTemplateId,
      customMessage: params.customMessage
    }
    return request({
      url: `/merchant/messages/sessions/${String(sessionId)}/send-coupon`,
      method: 'POST',
      data: payload
    })
  },

  // 标记消息已读
  markMessagesRead: (sessionId: number | string, messageIds?: Array<number | string>) => {
    // 如果传了messageIds且不为空，则传递数组；否则传空对象（标记整个会话）
    // 根据文档，不传messageIds时应该传空对象{}，让后端标记整个会话
    let requestData: any = {};
    if (messageIds && messageIds.length > 0) {
      // 后端期望Long数组，转换为数字
      requestData = { 
        messageIds: messageIds.map(id => {
          const numId = Number(id);
          return isNaN(numId) ? id : numId;
        })
      };
    }
    // 如果不传messageIds或为空，传空对象{}，让后端标记整个会话
    
    return request({
      url: `/merchant/messages/sessions/${String(sessionId)}/mark-read`,
      method: 'PUT',
      data: requestData
    })
  },

  // 获取可用优惠券列表
  getAvailableCoupons: () => {
    return request({
      url: '/merchant/messages/available-coupons',
      method: 'GET'
    })
  },

  // 删除消息会话
  deleteSession: (sessionId: number | string) => {
    return request({
      url: `/merchant/messages/sessions/${String(sessionId)}`,
      method: 'DELETE'
    })
  },

  // 获取消息通知设置
  getMessageNotificationSettings: () => {
    return request({
      url: '/merchant/messages/notification-settings',
      method: 'GET'
    })
  },

  // 更新消息通知设置
  updateMessageNotificationSettings: (params: {
    enableCustomerMessage?: boolean;
    enablePlatformMessage?: boolean;
    enableGroupMessage?: boolean;
    enableSound?: boolean;
    enableVibration?: boolean;
    quietHoursStart?: string;
    quietHoursEnd?: string;
  }) => {
    return request({
      url: '/merchant/messages/notification-settings',
      method: 'PUT',
      data: params
    })
  },

  // 旧版接口兼容（保留以防止旧代码调用出错）
  getMessageList: (params: any) => {
    return request({
      url: '/merchant/messages/sessions',
      method: 'GET',
      data: params
    })
  },

  getChatHistory: (sessionId: number | string, params?: any) => {
    return request({
      url: `/merchant/messages/sessions/${String(sessionId)}/history`,
      method: 'GET',
      data: params
    })
  },

  // ==================== 钱包管理相关 ====================
  
  // 查询账户余额
  getFinanceBalance: () => {
    return request({
      url: '/merchant/finance/balance',
      method: 'GET'
    })
  },

  // 查询流水列表
  getFinanceFlowList: (params?: {
    pageNum?: number;
    pageSize?: number;
    flowType?: number;        // 1-收入，2-支出
    businessType?: number;    // 业务类型
    startTime?: string;       // 开始时间（格式：yyyy-MM-dd HH:mm:ss）
    endTime?: string;         // 结束时间（格式：yyyy-MM-dd HH:mm:ss）
    flowNo?: string;          // 流水号
  }) => {
    return request({
      url: '/merchant/finance/flow-list',
      method: 'GET',
      data: params
    })
  },

  // 查询流水详情
  getFinanceFlowDetail: (flowId: number) => {
    return request({
      url: `/merchant/finance/flow/${flowId}`,
      method: 'GET'
    })
  },

  // 提现申请
  submitWithdraw: (params: {
    amount: number;           // 提现金额
    withdrawalCardId: number; // 提现银行卡ID
    remark?: string;          // 备注
  }) => {
    return request({
      url: '/merchant/finance/withdraw',
      method: 'POST',
      data: params
    })
  },

  // 查询提现记录列表
  getWithdrawList: (params?: {
    pageNum?: number;
    pageSize?: number;
    withdrawalStatus?: number;  // 1-申请中，2-处理中，3-成功，4-失败
    startTime?: string;         // 开始时间（格式：yyyy-MM-dd HH:mm:ss）
    endTime?: string;           // 结束时间（格式：yyyy-MM-dd HH:mm:ss）
    flowNo?: string;            // 流水号
  }) => {
    return request({
      url: '/merchant/finance/withdraw-list',
      method: 'GET',
      data: params
    })
  },

  // 旧版接口兼容（保留以防止旧代码调用出错）
  getWalletOverview: () => {
    return request({
      url: '/merchant/finance/balance',
      method: 'GET'
    })
  },

  // 获取银行卡列表
  getBankCards: () => {
    return request({
      url: '/merchant/bank-cards',
      method: 'GET'
    })
  },

  // 添加银行卡
  addBankCard: (params: any) => {
    return request({
      url: '/merchant/bank-cards',
      method: 'POST',
      data: params
    })
  },

  // 获取收支概览
  getFinancialOverview: () => {
    return request({
      url: '/merchant/financial/overview',
      method: 'GET'
    })
  },

  // 获取收支分类统计
  getCategoryStats: () => {
    return request({
      url: '/merchant/financial/category-stats',
      method: 'GET'
    })
  },

  // 获取收支明细
  getFinancialRecords: (params: any) => {
    return request({
      url: '/merchant/financial/records',
      method: 'GET',
      data: params
    })
  },

  // ==================== 公告管理相关 ====================
  
  // 查询公告列表
  getAnnouncementList: (params?: {
    pageNum?: number;
    pageSize?: number;
    title?: string;           // 公告标题（模糊查询）
    status?: number;          // 状态：0-草稿，1-发布，2-下线
    startTime?: string;       // 开始时间
    endTime?: string;         // 结束时间
  }) => {
    return request({
      url: '/merchant/announcement/list',
      method: 'GET',
      data: params
    })
  },

  // 新增公告
  createAnnouncement: (params: {
    title: string;
    content: string;
    status: number;           // 0-草稿，1-发布
    publishTime?: string;     // 发布时间（格式：yyyy-MM-dd HH:mm:ss）
  }) => {
    return request({
      url: '/merchant/announcement/add',
      method: 'POST',
      data: params
    })
  },

  // 获取公告详情
  getAnnouncementDetail: (announcementId: number) => {
    return request({
      url: `/merchant/announcement/${announcementId}`,
      method: 'GET'
    })
  },

  // 更新公告（只能更新草稿）
  updateAnnouncement: (announcementId: number, params: {
    title: string;
    content: string;
    publishTime?: string;     // 发布时间（格式：yyyy-MM-dd HH:mm:ss）
  }) => {
    return request({
      url: `/merchant/announcement/${announcementId}`,
      method: 'PUT',
      data: params
    })
  },

  // 发布公告（草稿转发布）
  publishAnnouncement: (announcementId: number) => {
    return request({
      url: `/merchant/announcement/${announcementId}/publish`,
      method: 'POST'
    })
  },

  // 下线公告
  offlineAnnouncement: (announcementId: number) => {
    return request({
      url: `/merchant/announcement/${announcementId}/offline`,
      method: 'POST'
    })
  },

  // 删除公告
  deleteAnnouncement: (announcementId: number) => {
    return request({
      url: `/merchant/announcement/${announcementId}`,
      method: 'DELETE'
    })
  },

  // 获取定制需求列表
  getCustomRequirements: (params?: any) => {
    return request({
      url: '/workbench/custom/requirements',
      method: 'GET',
      data: params
    })
  },

  // 接单定制需求
  acceptCustomRequirement: (params: any) => {
    return request({
      url: '/workbench/custom/accept',
      method: 'POST',
      data: params
    })
  },

  // 获取店铺活动列表
  getActivities: (params?: any) => {
    return request({
      url: '/workbench/activities/list',
      method: 'GET',
      data: params
    })
  },

  // 创建节日活动
  createFestivalActivity: (params: any) => {
    return request({
      url: '/workbench/activities/festival/create',
      method: 'POST',
      data: params
    })
  },

  // 创建满减活动
  createFullReductionActivity: (params: any) => {
    return request({
      url: '/workbench/activities/full-reduction/create',
      method: 'POST',
      data: params
    })
  },

  // 获取通知设置
  getNotificationSettings: () => {
    return request({
      url: '/merchant/notification-settings',
      method: 'GET'
    })
  },

  // 更新通知设置
  updateNotificationSettings: (params: any) => {
    return request({
      url: '/merchant/notification-settings',
      method: 'PUT',
      data: params
    })
  },

  // 应用推荐设置
  applyRecommendedSettings: () => {
    return request({
      url: '/merchant/notification-settings/recommended',
      method: 'POST'
    })
  },

  // 打印机设备管理
  managePrinterDevices: (params: any) => {
    return request({
      url: '/merchant/printers/devices',
      method: 'POST',
      data: params
    })
  },

  // ==================== 订单管理相关（新接口） ====================
  
  // 查询订单列表（新接口）
  getOrderListNew: (params?: {
    pageNum?: number;
    pageSize?: number;
    orderNo?: string;
    status?: number;
    paymentStatus?: number;
    pickupCode?: string;
    startTime?: string;
    endTime?: string;
  }) => {
    return request({
      url: '/merchant/order/list',
      method: 'GET',
      data: params
    })
  },

  // 获取订单详情（新接口）
  getOrderDetailNew: (orderId: number | string) => {
    return request({
      url: `/merchant/order/${orderId}`,
      method: 'GET'
    })
  },

  // 订单统计（按状态）
  getOrderStatistics: () => {
    return request({
      url: '/merchant/order/statistics',
      method: 'GET'
    })
  },

  // 今日订单概览
  getTodayOrderSummary: () => {
    return request({
      url: '/merchant/order/today-summary',
      method: 'GET'
    })
  },

  // 营业额统计
  getOrderAmountStatistics: (params?: {
    startTime?: string;
    endTime?: string;
  }) => {
    return request({
      url: '/merchant/order/amount-statistics',
      method: 'GET',
      data: params
    })
  },

  // 接单（新接口）
  acceptOrderNew: (orderId: number | string, params?: {
    estimatedMin?: number;
  }) => {
    return request({
      url: `/merchant/order/accept/${orderId}`,
      method: 'PUT',
      data: params
    })
  },

  // 批量接单
  batchAcceptOrders: (params: {
    orderIds: Array<number | string>;
    estimatedMin?: number;
  }) => {
    const orderIds = params.orderIds.map(id => Number(id));
    return request({
      url: '/merchant/order/batch-accept',
      method: 'PUT',
      data: {
        orderIds,
        estimatedMin: params.estimatedMin || 15
      }
    })
  },

  // 开始制作（新接口）
  startMaking: (orderId: number | string) => {
    return request({
      url: `/merchant/order/start-making/${orderId}`,
      method: 'PUT'
    })
  },

  // 制作完成（新接口）
  orderReady: (orderId: number | string) => {
    return request({
      url: `/merchant/order/ready/${orderId}`,
      method: 'PUT'
    })
  },

  // 完成订单（新接口）
  completeOrderNew: (orderId: number | string) => {
    return request({
      url: `/merchant/order/complete/${orderId}`,
      method: 'PUT'
    })
  },

  // 取消订单（新接口）
  cancelOrderNew: (params: {
    orderId: number | string;
    cancelReason: string;
  }) => {
    return request({
      url: '/merchant/order/cancel',
      method: 'PUT',
      data: {
        orderId: Number(params.orderId),
        cancelReason: params.cancelReason
      }
    })
  },

  // 打印订单
  printOrder: (orderId: number | string, params?: {
    printerId?: number | string;
  }) => {
    return request({
      url: `/merchant/order/print/${orderId}`,
      method: 'POST',
      data: params
    })
  },

  // ==================== 打印机管理相关（新接口） ====================
  
  // 查询打印机列表（新接口）
  getPrinterList: () => {
    return request({
      url: '/merchant/printer/list',
      method: 'GET'
    })
  },

  // 获取打印机详情（新接口）
  getPrinterDetail: (printerId: number | string) => {
    return request({
      url: `/merchant/printer/${printerId}`,
      method: 'GET'
    })
  },

  // 新增打印机（新接口）
  addPrinter: (params: {
    printerName: string;
    printerBrand: string;
    printerModel: string;
    printerSn: string;
    printerKey?: string;
    connectionType: number;  // 1-云打印，2-蓝牙，3-WiFi，4-USB
    ipAddress?: string;
    port?: number;
    printWidth?: number;  // 默认58
    autoPrintOrder?: number;  // 默认1
    printCopies?: number;  // 默认1
  }) => {
    return request({
      url: '/merchant/printer',
      method: 'POST',
      data: params
    })
  },

  // 修改打印机（新接口）
  updatePrinter: (params: {
    printerId: number | string;
    printerName: string;
    printerBrand: string;
    printerModel: string;
    printerSn: string;
    printerKey?: string;
    connectionType: number;
    ipAddress?: string;
    port?: number;
    printWidth?: number;
    autoPrintOrder?: number;
    printCopies?: number;
  }) => {
    return request({
      url: '/merchant/printer',
      method: 'PUT',
      data: {
        ...params,
        printerId: Number(params.printerId)
      }
    })
  },

  // 更新打印机状态
  updatePrinterStatus: (printerId: number | string, status: number) => {
    return request({
      url: `/merchant/printer/status/${printerId}`,
      method: 'PUT',
      data: { status }
    })
  },

  // 删除打印机（新接口）
  deletePrinter: (printerId: number | string) => {
    return request({
      url: `/merchant/printer/${printerId}`,
      method: 'DELETE'
    })
  },

  // 批量删除打印机
  batchDeletePrinters: (params: {
    printerIds: Array<number | string>;
  }) => {
    const printerIds = params.printerIds.map(id => Number(id));
    return request({
      url: '/merchant/printer/batch-delete',
      method: 'DELETE',
      data: { printerIds }
    })
  },

  // 设置默认打印机
  setDefaultPrinter: (printerId: number | string) => {
    return request({
      url: `/merchant/printer/set-default/${printerId}`,
      method: 'PUT'
    })
  },

  // 测试打印
  testPrint: (printerId: number | string) => {
    return request({
      url: `/merchant/printer/test/${printerId}`,
      method: 'POST'
    })
  },

  // ==================== 个人中心相关 ====================
  
  // 获取商家信息详情
  getMerchantInfo: () => {
    return request({
      url: '/merchant/info',
      method: 'GET'
    })
  },

  // 获取商家个人信息
  getPersonalInfo: () => {
    return request({
      url: '/merchant/info/personal-info',
      method: 'GET'
    })
  },

  // 修改商家个人信息
  updateMerchantInfo: (params: {
    merchantName?: string;        // 商家名称
    contactPerson?: string;       // 联系人
    contactPhone?: string;        // 联系电话
    avatarUrl?: string;          // 头像URL
    address?: string;            // 地址
    latitude?: number;           // 纬度
    longitude?: number;          // 经度
    smsCode?: string;            // 短信验证码（修改手机号时必填）
  }) => {
    return request({
      url: '/merchant/profile/update',
      method: 'PUT',
      data: params
    })
  },

  // 更新商家个人资料（昵称/邮箱/性别等）
  updatePersonalInfo: (params: {
    nickName?: string;
    avatar?: string;
    email?: string;
    sex?: string | number;
    phonenumber?: string;
    smsCode?: string;
  }) => {
    return request({
      url: '/merchant/info/update-personal',
      method: 'PUT',
      data: params
    })
  },

  // 发送个人信息修改验证码
  sendPersonalInfoSms: (phone: string) => {
    return request({
      url: `/merchant/auth/sms/send/${phone}`,
      method: 'POST'
    })
  },

  // 上传商家头像
  uploadAvatar: (filePath: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('merchantToken')
      
      wx.uploadFile({
        url: API_CONFIG.baseURL + '/merchant/info/upload-avatar',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          try {
            let responseData: any = res.data
            if (typeof res.data === 'string') {
              responseData = JSON.parse(res.data)
            }

            if (responseData && responseData.code === 200) {
              resolve(responseData)
            } else {
              wx.showToast({
                title: (responseData && responseData.msg) || '上传失败',
                icon: 'none'
              })
              reject(responseData)
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(error)
        }
      })
    })
  },

  // 更新商家营业状态
  updateMerchantStatus: (status: number) => {
    return request({
      url: '/merchant/info/status',
      method: 'PUT',
      data: { status }
    })
  },

  // 查询门店营业状态
  getShopStatus: () => {
    return request({
      url: '/merchant/shop/status',
      method: 'GET'
    })
  },

  // 获取商家钱包信息
  getWalletInfo: () => {
    return request({
      url: '/merchant/wallet/info',
      method: 'GET'
    })
  },

  // 获取钱包收支明细
  getWalletFlowList: (params: {
    pageNum?: number;
    pageSize?: number;
    flowType?: number;
    businessType?: number;
    startDate?: string;
    endDate?: string;
  }) => {
    return request({
      url: '/merchant/wallet/flow-list',
      method: 'GET',
      data: params
    })
  },

  // 申请提现
  applyWithdraw: (params: {
    amount: number;
    cardId: string;
    remark?: string;
  }) => {
    return request({
      url: '/merchant/wallet/withdraw',
      method: 'POST',
      data: params
    })
  },

  // 修改密码
  changePassword: (params: {
    oldPassword: string;
    newPassword: string;
    confirmPassword: string;
  }) => {
    return request({
      url: '/merchant/info/account/change-password',
      method: 'PUT',
      data: params
    })
  },

  // 退出登录
  logout: () => {
    return request({
      url: '/merchant/info/account/logout',
      method: 'POST'
    })
  },

  // 注销账号
  deleteAccount: (params: {
    password: string;
    reason: string;
  }) => {
    return request({
      url: '/merchant/info/account/delete',
      method: 'DELETE',
      data: params
    })
  },

  // ==================== 优惠券管理相关 ====================

  /**
   * 获取优惠券列表
   * @param params 查询参数
   */
  getCouponList: (params?: any) => {
    return request({
      url: '/merchant/coupon/binding/list',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取优惠券详情
   * @param bindingId 绑定ID
   */
  getCouponDetail: (bindingId: string) => {
    return request({
      url: `/merchant/coupon/binding/${bindingId}`,
      method: 'GET'
    })
  },

  /**
   * 创建优惠券
   * @param params 优惠券数据
   */
  createCoupon: (params: any) => {
    return request({
      url: '/merchant/coupon/binding',
      method: 'POST',
      data: params
    })
  },

  /**
   * 更新优惠券
   * @param params 优惠券数据
   */
  updateCoupon: (params: any) => {
    return request({
      url: '/merchant/coupon/binding',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 删除优惠券
   * @param bindingIds 绑定ID数组
   */
  deleteCoupon: (bindingIds: string[]) => {
    return request({
      url: `/merchant/coupon/binding/${bindingIds.join(',')}`,
      method: 'DELETE'
    })
  },

  // ==================== 区域绑定管理相关 ====================

  /**
   * 获取平台区域列表
   * @param params 查询参数
   */
  getRegionList: (params?: any) => {
    return request({
      url: '/platform/regions/list',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取商家区域绑定列表
   * @param params 查询参数
   */
  getMerchantRegionBindingList: (params?: any) => {
    return request({
      url: '/merchant/region/binding/list',
      method: 'GET',
      data: params
    })
  },

  /**
   * 获取区域绑定详情
   * @param bindingId 绑定ID
   */
  getRegionBindingDetail: (bindingId: string) => {
    return request({
      url: `/merchant/region/binding/${bindingId}`,
      method: 'GET'
    })
  },

  /**
   * 创建区域绑定
   * @param params 区域绑定数据
   */
  createRegionBinding: (params: any) => {
    return request({
      url: '/merchant/region/binding',
      method: 'POST',
      data: params
    })
  },

  /**
   * 更新区域绑定
   * @param params 区域绑定数据
   */
  updateRegionBinding: (params: any) => {
    return request({
      url: '/merchant/region/binding',
      method: 'PUT',
      data: params
    })
  },

  /**
   * 删除区域绑定
   * @param bindingIds 绑定ID数组
   */
  deleteRegionBinding: (bindingIds: string[]) => {
    return request({
      url: `/merchant/region/binding/${bindingIds.join(',')}`,
      method: 'DELETE'
    })
  },

  /**
   * 获取用户最新订单详情
   * @param sessionId 会话ID
   */
  getUserLatestOrder: (sessionId: string) => {
    return request({
      url: `/merchant/messages/sessions/${sessionId}/latest-order`,
      method: 'GET'
    })
  }
}

/**
 * 文件上传相关接口
 */
export const UploadAPI = {
  // 上传通用文件（资质文件、商家图片等）
  uploadFile: (filePath: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('merchantToken')
      
      // 调试日志
      console.log('=== 上传文件 ===')
      console.log('Token:', token)
      console.log('文件路径:', filePath)
      console.log('================')
      
      if (!token) {
        const errorMsg = 'Token不存在，请先登录'
        console.error(errorMsg)
        wx.showToast({
          title: errorMsg,
          icon: 'none'
        })
        reject({ code: 401, msg: errorMsg })
        return
      }
      
      wx.uploadFile({
        url: API_CONFIG.baseURL + '/merchant/common/upload',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': `Bearer ${token}`
        },
        success: (res) => {
          try {
            let responseData: any = res.data
            if (typeof res.data === 'string') {
              responseData = JSON.parse(res.data)
            }

            if (responseData && responseData.code === 200) {
              resolve(responseData)
            } else {
              wx.showToast({
                title: (responseData && responseData.msg) || '上传失败',
                icon: 'none'
              })
              reject(responseData)
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: (error) => {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          })
          reject(error)
        }
      })
    })
  },

  // 上传资质文件（兼容旧代码）
  uploadQualificationFile: (filePath: string, _fileType?: number): Promise<any> => {
    return UploadAPI.uploadFile(filePath)
  },

  // 上传店铺背景图
  uploadStoreBackground: (filePath: string): Promise<any> => {
    return new Promise((resolve, reject) => {
      const token = wx.getStorageSync('merchantToken')
      
      wx.uploadFile({
        url: API_CONFIG.baseURL + '/merchant/store/upload-background',
        filePath: filePath,
        name: 'file',
        header: {
          'Authorization': token ? `Bearer ${token}` : ''
        },
        success: (res) => {
          try {
            let responseData: any = res.data
            if (typeof res.data === 'string') {
              responseData = JSON.parse(res.data)
            }

            if (responseData && responseData.code === 200) {
              resolve(responseData)
            } else {
              reject(responseData)
            }
          } catch (error) {
            reject(error)
          }
        },
        fail: reject
      })
    })
  }
}

// 导出默认请求方法
export default request

// 兼容旧版本导出
export const ShopAPI = MerchantAPI
export const OrderAPI = {
  getOrderList: MerchantAPI.getOrderList,
  getOrderDetail: MerchantAPI.getOrderDetail,
  acceptOrder: MerchantAPI.acceptOrder,
  rejectOrder: MerchantAPI.cancelOrder,
  startPreparing: MerchantAPI.startCooking,
  startDelivering: MerchantAPI.readyForPickup,
  completeOrder: () => Promise.resolve({ data: {} }),
  getOrderStats: () => Promise.resolve({ data: {} })
}
export const MessageAPI = {
  getMessageList: MerchantAPI.getMessageList,
  markMessageRead: () => Promise.resolve({ data: {} }),
  markMessagesRead: () => Promise.resolve({ data: {} }),
  markAllRead: () => Promise.resolve({ data: {} }),
  getUnreadCount: () => Promise.resolve({ data: {} })
}